package com.report.wx.mp.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.report.dto.response.WebMemberRes;
import com.report.service.IMemberService;
import com.report.socket.WebSocketServer;
import com.zmh.framework.redis.RedisCache;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 微信关注
 * @author summer
  */
@Component
@Slf4j
public class ScanHandler implements WxMpMessageHandler {


    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {

        log.info("openId:{}", wxMessage.getFromUser());
        String ticket = wxMessage.getTicket();
        log.info("ticket:{}", ticket);
        WxMpUser wxMpUser = wxMpService.getUserService().userInfo(wxMessage.getFromUser());
        log.info("unionId:{}", wxMpUser.getUnionId());

        IMemberService memberService = SpringUtil.getBean(IMemberService.class);
        RedisCache redisCache = SpringUtil.getBean(RedisCache.class);
        String type = redisCache.get("wx:" + ticket);
        WebSocketServer socketServer = SpringUtil.getBean(WebSocketServer.class);
        String message="";
        if(StrUtil.isNotEmpty(type)){
            int add=Integer.parseInt(type);
            //登录
            if(add==1){
                WebMemberRes memberRes = memberService.saveWxMember(wxMessage.getFromUser(),wxMpUser.getUnionId());
                memberRes.setTicket(ticket);
                socketServer.sendMessage(memberRes);
                message="登录成功";
            }else{ //更换
                message="绑定微信";
                Boolean isBand = memberService.updateWxMember(wxMessage.getFromUser());
                if(isBand){
                    socketServer.sendErrorMessage(wxMessage.getTicket());
                }else{
                    WebMemberRes memberRes=new WebMemberRes();
                    memberRes.setTicket(wxMessage.getTicket());
                    socketServer.sendMessage(memberRes );
                }

            }
        }


        return WxMpXmlOutMessage.TEXT().fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                .content(message).build();
    }
}



